package algorithm.linear;

import java.util.Arrays;

/**
 * 顺序栈类 时间复杂度(O1)
 * @param <E>
 */
public class SeqStack<E> implements SStack {
    //存储栈的数据元素的数组
    private Object value[];
    //栈顶元素的下标
    private int top;

    //构建指定容量的栈
    public SeqStack(int capacity) {
        this.value = new Object[Math.abs(capacity)];
        this.top = -1;
    }

    public SeqStack() {
        this(10);
    }

    //判断是否为空，若空返回true
    public boolean isEmpty() {
        return this.top == -1;
    }

    //元素入栈，操作成功返回true
    public boolean push(Object element) {
        if ( element == null )
            return false;
        //若栈满，则扩容
        if (this.top == value.length -1) {
            Object[] temp = this.value;
            this.value = new Object[temp.length*2];
            for(int i=0;i<temp.length;i++)
                this.value[i] = temp[i];
        }
        this.top++;
        this.value[this.top] = element;
        return true;
    }

    //出栈，返回当前栈顶元素，若栈为空则返回null
    public Object pop() {
        if ( !isEmpty() )
            return this.value[this.top--];
        return null;
    }

    //取栈顶元素，未出栈，栈无素未改变
    public Object get() {
        if (!isEmpty())
            return this.value[this.top];
        return null;
    }

    @Override
    public String toString() {
        return "SeqStack{" +
                "value=" + Arrays.toString(value) +
                ", top=" + top +
                '}';
    }
}
